<template>
  <ContentWrap>
    <!-- 操作按钮栏 -->
    <el-row>
      <el-col :span="24">
        <el-form-item>
          <el-button type="primary" @click="handleUpload">上传</el-button>
          <el-button 
            type="success" 
            @click="handleDownloadSelected"
            :disabled="selectedRows.length === 0"
          >
            下载
          </el-button>
          <el-button 
            type="danger" 
            @click="handleDeleteSelected"
            :disabled="selectedRows.length === 0"
            v-hasPermi="['business:prod-picture:delete']"
          >
            删除
          </el-button>
        </el-form-item>        
      </el-col>
    </el-row>
    
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="图片名称"
        align="center"
        prop="pictureName"
      >
        <template #default="{ row }">
          <el-link type="primary" @click="handlePreview(row)">
            {{ row.pictureName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="pictureType" />
      <el-table-column label="上传人" align="center" prop="updateMan" />
      <el-table-column label="上传时间" align="center" prop="updateTime" />
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 上传弹窗 -->
  <UploadDialog ref="uploadDialogRef" @success="getList" />
  <ImagePreview ref="imagePreviewRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { ProdPictureApi, ProdPictureVO } from '@/api/product/prodpicture'
import { formatDate } from '@/utils/formatTime'
import UploadDialog from './ProdPictureUploadForm.vue'
import ImagePreview from '@/components/ImagePreview.vue'

const imagePreviewRef = ref()
const uploadDialogRef = ref()
const route = useRoute()
const userStore = useUserStore()
const loading = ref(false)
const total = ref(0)
const selectedRows = ref<ProdPictureNewPageVO[]>([])
const list = ref<ProdPictureNewPageVO[]>([])

// 从URL参数获取产品ID
const getProductIdFromUrl = () => {
  // 尝试从URL查询参数获取ID
  const idFromQuery = route.query.id;
  
  // 如果查询参数中有ID，优先使用
  if (idFromQuery) {
    return idFromQuery.toString();
  }
  
  // 尝试从路由参数获取ID
  const idFromParams = route.params.id;
  if (idFromParams) {
    return Array.isArray(idFromParams) ? idFromParams[0] : idFromParams;
  }
  
  // 尝试从props获取产品ID
  if (props.productInfo?.prodId) {
    return props.productInfo.prodId.toString();
  }
  
  console.warn('无法从URL或props获取产品ID');
  return '';
}

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  prodId: '', // 将从URL获取的ID存储在这里
})

// 组件页面传参
const props = defineProps<{
  productInfo?: {
    prodId?: string | number
    name?: string
    nameEn?: string
    specs?: string
  }
}>()

// 监听URL变化
watch(
  () => route.query.id,
  (newId) => {
    if (newId) {
      queryParams.prodId = newId.toString();
      console.log('URL中的产品ID已更新:', queryParams.prodId);
      getList();
    }
  }
);

// 初始化时设置产品ID
const initializeProductId = () => {
  const productId = getProductIdFromUrl();
  if (productId) {
    queryParams.prodId = productId;
    console.log('初始化产品ID:', queryParams.prodId);
    getList();
  }
}

// 获取数据
const getList = async () => {
  // 如果没有产品ID，则不发送请求
  if (!queryParams.prodId) {
    console.warn('缺少产品ID，无法获取图片列表');
    return;
  }
  
  loading.value = true;
  try {
    console.log('请求参数:', queryParams);
    const res = await ProdPictureApi.getProdPictureNewPage(queryParams);
    list.value = res.list || [];
    total.value = res.total || 0;
    console.log('获取图片列表成功，数量:', list.value.length);
  } catch (error) {
    console.error('获取图片列表失败:', error);
    ElMessage.error('获取图片列表失败，请重试');
  } finally {
    loading.value = false;
  }
}

// 下载选中的图片
const handleDownloadSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要下载的图片');
    return;
  }
  
  selectedRows.value.forEach(row => {
    if (row.pictureUrl) {
      const link = document.createElement('a');
      link.href = row.pictureUrl;
      link.download = row.pictureName || 'download';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  });
  
  ElMessage.success(`开始下载 ${selectedRows.value.length} 个文件`);
}

// 删除选中的图片
const handleDeleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的图片');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 张图片吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const ids = selectedRows.value.map(item => item.id);
    const deletePromises = ids.map(id => ProdPictureApi.deleteProdPicture(id));
    await Promise.all(deletePromises);
    
    ElMessage.success(`成功删除 ${ids.length} 张图片`);
    selectedRows.value = [];
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

// 预览图片
const handlePreview = (row: any) => {
  const url = row.pictureUrl;
  if (url) {
    imagePreviewRef.value?.open(url, row.pictureName);
  } else {
    ElMessage.warning('图片链接为空');
  }
}

// 处理选择变化
const handleSelectionChange = (val: ProdPictureNewPageVO[]) => {
  selectedRows.value = val;
}

// 打开上传弹窗
const handleUpload = () => {
  const uploadBy = userStore.getUser.name || '未知用户';
  const createTime = new Date().toISOString();
  
  // 确保传递正确的产品ID
  uploadDialogRef.value?.open({
    uploadBy,
    createTime,
    prodId: queryParams.prodId // 使用从URL获取的ID
  });
  
  console.log('打开上传弹窗，产品ID:', queryParams.prodId);
}

// 初始化
onMounted(() => {
  initializeProductId();
});
</script>

<style scoped>
.el-form-item {
  margin-bottom: 18px;
}
</style>